package cn.lliiooll.ippzonetoolbox.task;

import lombok.Getter;
import lombok.SneakyThrows;

public class PTask {
    @Getter
    private Runnable runable;
    @Getter
    private Runnable finished;
    private Thread task;
    private boolean cancel = false;

    public PTask onFinished(Runnable runnable) {
        this.finished = runnable;
        return this;
    }

    public PTask setRunnable(Runnable runable) {
        this.runable = runable;
        return this;
    }

    public void start() {
        this.task = new Thread(runable);
        this.task.start();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                while (PTask.this.task.isAlive() && !cancel) {
                }
                if (!cancel) {
                    if (PTask.this.finished != null) PTask.this.finished.run();
                }
            }
        }).start();
    }

    public void cancel() {
        cancel = true;
        try {
            this.task.stop();
        } catch (Exception e) {

        }
    }
}
